package com.kim.openapi;


import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class KimOpenApiManager {

    private static final String TAG = "KimOpenApiManager";
    private Context mContext;

    private IKimOpenApiManagerService mService;

    private IBinder b;
    private static KimOpenApiManager mInstance;
    private boolean connected;

    private KimOpenApiManager(Context context) {
        mContext = context.getApplicationContext();
        bindKimOpenApiManagerService(conn);
    }

    public void unRegister() {
        if (connected) {
            mContext.unbindService(conn);
        }
    }

    public int addApn(KimApn apn) {
        if (!connected) {
            Log.e(TAG, "getService: connected= false");
        }

        int ret = 0;
        try {
            ret = getService().addApn(apn);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return ret;
    }

    private IKimOpenApiManagerService getService() {

        if (mService != null) {
            return mService;
        }
        mService = IKimOpenApiManagerService.Stub.asInterface(b);
        return mService;
    }


    public static synchronized KimOpenApiManager register(Context context) {
        if (mInstance == null) {
            mInstance = new KimOpenApiManager(context);
        }
        return mInstance;
    }

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            b = service;
            connected = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            connected = false;
        }
    };

    private void bindKimOpenApiManagerService(ServiceConnection serviceConnection) {
        Intent intent = new Intent();
        intent.setPackage("com.kim.openapi");
        intent.setAction("kim.openapi.action.start");
        mContext.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

}
